package com.jsj.subway.ai.agent.chat;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import com.jsj.subway.ai.common.Role;
import com.jsj.subway.ai.demo.dto.ChatDTO;
import com.jsj.subway.ai.largemodel.AliClient;
import com.jsj.subway.ai.largemodel.models.AliModelCompletionResponse;
import com.jsj.subway.ai.largemodel.models.Message;
import com.jsj.subway.ai.utils.LocalCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.jsj.subway.ai.demo.constants.Constants.sameMap;

@Service
@Slf4j
public class IntentRecognitionServiceImpl implements IntentRecognitionService{


    @Value("${kb.systemPrompt3}")
    private String systemPrompt3;

    @Value("${kb.systemPrompt}")
    private String systemPrompt;

    //文本生成意图识别
    @Value("${kb.systemPrompt4}")
    private String systemPrompt4;

    @Autowired
    private AliClient aliClient;

    @Autowired
    private LocalCache localCache;


    @Override
    public Pair<Integer,List<Message>> intentRecognition(List<Message> messageContext, Long sessionId) {

        List<Message> context = new ArrayList<>();
        List<Message> returnContext = new ArrayList<>();
        Message systemMsg = new Message();
        String system = makeSystemPrompt(systemPrompt, sessionId, messageContext.get(0));
        log.info("重合闸意图识别提示词：{}",system);
        systemMsg.setRole("system");
        systemMsg.setContent(system);
        context.add(systemMsg);

        //String lastContent = StrUtil.format(modelHistorySummarize, history_prompt, mme.getContent());
        context.addAll(messageContext);

        AliModelCompletionResponse response = aliClient.completionsChat(context);
        //0-否 ：直接输出结束 。agent 返回：固定内容
        //1-是 ：继续调用模型 带着返回值调用。（prompt）
        //2-不相关 ：不带prompt调用模型
        if (response.getErr_code() == 0) {
            List<Message> allMessages = response.toMessage();
            ChatDTO.MessageRecord result = ChatDTO.toMessageRecord(allMessages, false);
            String content = (String) result.getContent();
            log.info("当前意图识别的输出是：{}",content);
            if(content.contains("0")){
                returnContext.add(Message.builder().role(Role.ASSISTANT.getLabel()).content("固定的返回内容").build());
                return new Pair<>(0,returnContext);
            }else if(content.contains("1")){
                int counter = localCache.getCounter();
                String s = sameMap.get(counter);
                returnContext.add(Message.builder().content(s).role(Role.USER.getLabel()).build());
                //returnContext.add(Message.builder().content(s).role(Role.ASSISTANT.getLabel()).build());
                return new Pair<>(1,returnContext);
            }else if(content.contains("2")){

                return new Pair<>(2,messageContext);
            }else {
                log.info("当前意图识别无法判断0，1，2 情况");
                //异常情况
                return new Pair<>(2,messageContext);
            }
        } else {
            log.info("会话失败 ,message={}",  response.getErr_msg());
            return null;
        }
    }

    @Override
    public Pair<Integer,List<Message>> intentRecognitionCreatePDF(List<Message> messageContext,Long sessionId) {

        List<Message> context = new ArrayList<>();
        List<Message> returnContext = new ArrayList<>();
        Message systemMsg = new Message();
        String s = makeSystemPrompt(systemPrompt4, sessionId, messageContext.get(0));
        log.info("生成报告意图识别提示词：{}",s);
        systemMsg.setRole("system");
        systemMsg.setContent(s);
        context.add(systemMsg);

        //String lastContent = StrUtil.format(modelHistorySummarize, history_prompt, mme.getContent());
        context.addAll(messageContext);

        AliModelCompletionResponse response = aliClient.completionsChat(context);
        //1. 如果content所表达的意思是回答'需要生成报告'，那么请你回复：1；
        //2. 否则，一律回复：0

        if (response.getErr_code() == 0) {
            List<Message> allMessages = response.toMessage();
            ChatDTO.MessageRecord result = ChatDTO.toMessageRecord(allMessages, false);
            String content = (String) result.getContent();
            log.info("当前生成文档意图识别的输出是：{}",content);
            if(content.contains("0")){
                return new Pair<>(0,messageContext);
            }else if(content.contains("1")){
                returnContext = createPDF(sessionId);
                //没有上下文 则返回用户内容
                if(CollectionUtil.isEmpty(returnContext)){

                    return new Pair<>(0,messageContext);
                }
                return new Pair<>(1,returnContext);
            }else {
                log.info("当前意图识别无法判断0，1情况");
                //异常情况
                return new Pair<>(0,messageContext);
            }
        } else {
            log.info("会话失败 ,message={}",  response.getErr_msg());
            return null;
        }
    }


    public List<Message> createPDF (Long sessionId){
        Deque<ChatDTO.MessageRecord> messageRecordsFromCache = localCache.getMessageRecordsFromCache(sessionId);

        if(CollectionUtil.isEmpty(messageRecordsFromCache)){
            return new ArrayList<>();
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("以下是本次故障排查完整过程的对话记录，格式为");
        for (ChatDTO.MessageRecord messageRecord : messageRecordsFromCache) {
            stringBuilder.append(messageRecord.getTime()).append(",").append(messageRecord.getRole()).append(",").append(messageRecord.getContent()).append("\n");
        }

        List<Message> context = new ArrayList<>();
        Message systemMsg = new Message();
        systemMsg.setRole("system");
        systemMsg.setContent(systemPrompt3);
        context.add(systemMsg);
        context.add(Message.toMessage(stringBuilder.toString(),Role.USER.getLabel()));

        return context;

    }

    private String makeSystemPrompt(String systemPrompt,Long sessionId,Message userMessage){
        String historyMessage = StringUtils.EMPTY;
        Deque<ChatDTO.MessageRecord> messageRecordsFromCache = localCache.getMessageRecordsFromCache(sessionId);
        List<ChatDTO.MessageRecord> collect = messageRecordsFromCache.stream().filter(record -> StringUtils.isNotBlank(record.getRole()) && Objects.equals(record.getRole(), Role.ASSISTANT.getLabel())).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(collect)){
            historyMessage  = collect.get(collect.size()-1).getContent().toString();
           // historyMessage  = (String) collect.getLast().getContent();
        }
        return StrUtil.format(systemPrompt,historyMessage,userMessage.getContent());
    }
}
